﻿using System;
using System.Data;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Domain;
using Casamiel.Domain.Response;
using Enyim.Caching;
using MediatR;
using Microsoft.Extensions.Options;

namespace Casamiel.Application.Commands.MemberTicket
{

	/// <summary>
	/// 
	/// </summary>
	public sealed class GetTicketCommandHandler : BaseCommandHandler, IRequestHandler<GetTicketCommand, BaseResult<string>>
	{
		private readonly IMemberRepository _memberRepository;
		private readonly IMemberCardRepository  _memberCardRepository;
		private readonly IMemberTicketGiveRepository  _memberTicketGiveRepository;
		private readonly ICasaMielSession _session;
		private readonly IMemcachedClient _memcachedClient;
		private readonly string _memcachedPrex;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="memberRepository"></param>
		/// <param name="memberTicketGiveRepository"></param>
		/// <param name="memberCardRepository"></param>
		/// <param name="netICService"></param>
		/// <param name="httpClientFactory"></param>
		/// <param name="settings"></param>
		/// <param name="casaMielSession"></param>
		/// <param name="memcachedClient"></param>
		public GetTicketCommandHandler(IMemberRepository memberRepository, IMemberTicketGiveRepository memberTicketGiveRepository, IMemberCardRepository memberCardRepository, INetICService netICService,
			IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings, ICasaMielSession casaMielSession
		, IMemcachedClient memcachedClient) : base(netICService, httpClientFactory, settings)

		{
			_memberRepository = memberRepository;
			_memberTicketGiveRepository = memberTicketGiveRepository;
			_session = casaMielSession;
			_memberCardRepository = memberCardRepository;
			_memcachedClient = memcachedClient;
			_memcachedPrex = settings.Value.MemcachedPre;
		}

		public async Task<BaseResult<string>> Handle(GetTicketCommand request, CancellationToken cancellationToken)
		{
			if (request is null) {
				throw new ArgumentNullException(nameof(request));
			}

			var coupongive = await _memberTicketGiveRepository.FindAsync<ICasaMielSession>(request.ForwardCode).ConfigureAwait(false);
			if (coupongive == null) {
				return new BaseResult<string>("", 9999, "赠券信息不存在");
			}
			if (coupongive.Status == -1) {
				return new BaseResult<string>("", 9999, "转赠信息已过期");
			}
			if (coupongive.Status == 1) {
				return new BaseResult<string>("", 9999, "券已被领取");
			}

			var _cachekey = _memcachedPrex + Constant.GETTICKET + coupongive.Ticketid;

			var trynum = _memcachedClient.Increment(_cachekey, 1, 1);

			if (trynum > 1) {

				var coupongive1 = await _memberTicketGiveRepository.FindAsync<ICasaMielSession>(request.ForwardCode).ConfigureAwait(false);
				if (coupongive1 == null) {
					return new BaseResult<string>("", 9999, "赠券信息不存在");
				}
				if (coupongive1.Status == -1) {
					return new BaseResult<string>("", 9999, "赠券信息已过期");
				}
				if (coupongive1.Status == 1) {
					return new BaseResult<string>("", 0, "领取成功");
				}
			}

			var cardinfo = await _memberCardRepository.GetBindCardAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
			//var member = await _memberRepository.FindAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);

			if (cardinfo == null) {
				return new BaseResult<string>("", 9999, "您还没有会员卡不能领优惠券");
			}
			//if (member == null) {
			//	member = new Domain.Entity.Member {
			//		Mobile = request.Mobile,
			//		CreateDate = DateTime.Now
			//	};
			//	await _memberRepository.SaveAsync<ICasaMielSession>(member).ConfigureAwait(false);
			//}
			coupongive.Mobile = request.Mobile;
			coupongive.LastTime = DateTime.Now;
			coupongive.Status = 1;
			ICResult IcRsp;
			try {
				IcRsp = await NetICService.Icticketchange(new Domain.Request.IcticketchangeRequest {
					Ticketid = $"{coupongive.Ticketid}",
					Cardno=cardinfo.CardNO
				}).ConfigureAwait(false);
				if (IcRsp.code != 0) {
					_memcachedClient.Remove(_cachekey);
					return new BaseResult<string>("", IcRsp.code, IcRsp.msg);
				}
			} catch (Exception) {
				_memcachedClient.Remove(_cachekey);
				throw;
			}


		 
			try {

				var success=	await _memberTicketGiveRepository.UpdateAsync<ICasaMielSession>(coupongive).ConfigureAwait(false);
				if (success) {
					return new BaseResult<string>("", 0, "领取成功");
				}
				return new BaseResult<string>("", 9999, "领优惠券出错了");

			} catch (Exception ex) {
				_memcachedClient.Remove(_cachekey);
				LoggerSystemErrorInfo.Error($"{ex.StackTrace}");
				return new BaseResult<string>("", 9999, "领会员券出错了");
			}

			 
		}
	}
}
